<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Exception;
use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Uploadify as ModelUploadify;
use Hangpu888\Hpadmin\model\UploadifyCate;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\UploadsManager;
use Shopwwi\WebmanFilesystem\Facade\Storage;

class Uploadify extends Controller
{
    /**
     * 上传附件
     *
     * @return void
     */
    public function upload()
    {
        try {
            // 获取数据
            $cid = request()->get('cid');
            $key = request()->get('key','file');
            $file = request()->file($key);
            // 数据验证
            if (!$file) {
                throw new Exception('文件上传出错');
            }
            if (!$cid) {
                throw new Exception('请选择上传分类');
            }
            $category = UploadifyCate::where(['id'=> $cid])->find();
            if (!$category) {
                throw new Exception('上传分类出错');
            }
            // 上传扩展
            $getUploadExtension = $file->getUploadExtension();
            // 上传文件名称
            $fileMD5 = md5(date('Y-m-d H:i:s').get_random());
            $fileName = "{$fileMD5}.{$getUploadExtension}";
            $saveName = "{$category->dir_name}/{$fileName}";

            //上传文件至云端附件
            $qiniu = new UploadsManager;
            if ($qiniu->upload($file->getPathname(),$saveName,$category->dir_name)) {
                return Json::success('上传成功');
            }else{
                throw new Exception('上传失败');
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 显示附件列表
     *
     * @return void
     */
    public function index()
    {
        // 获取数据
        $cid = request()->get('cid');
        $page = request()->get('page',1);
        $limit = request()->get('limit',30);
        $ext = request()->get('ext');
        $width = request()->get('width',0);
        $height = request()->get('height',0);
        $extFormat = ['jpg','png','gif'];

        // 查询条件
        $map = [];
        if ($cid) {
            $map[] = ['cid','=',$cid];
        }
        if ($ext) {
            $ext_format = explode(',',$ext);
            $map[] = ['format','in',$ext_format];
            if (count(array_intersect($ext_format, $extFormat)) !== 0) {
                // 图片尺寸查询
                if ($width && $height) {
                    $map[] = ['width','=',$width];
                    $map[] = ['height','=',$height];
                }
            }
        }else{
            // 图片尺寸查询
            if ($width && $height) {
                $map[] = ['width','=',$width];
                $map[] = ['height','=',$height];
            }
        }

        // 查询数据
        $field = [
            'upload.*',
            'cate.title as cate_title'
        ];
        $data = ModelUploadify::alias('upload')
        ->join('uploadify_cate cate','cate.id=upload.cid')
        ->where($map)
        ->order('upload.id desc')
        ->field($field)
        ->paginate([
            'page'          => $page,
            'list_rows'     => $limit
        ])
        ->each(function($item)use($extFormat){
            if (in_array($item['format'],$extFormat)) {
                $item->type = "image";
            }else{
                $item->type = "file";
            }
            $item->url = Storage::url($item->path);
            return $item;
        })->toArray();
        return Json::successRes($data);
    }

    /**
     * 修改附件名称
     *
     * @return void
     */
    public function edit()
    {
        try {
            //获取数据
            $id = request()->get('id');
            $post = request()->post();

            // 数据验证
            if (!isset($post['title']) || empty($post['title'])) {
                throw new Exception('请输入附件名称');
            }

            // 数据操作
            $map['id'] = $id;
            $model = ModelUploadify::where($map)->find();
            $model->title = $post['title'];
            if ($model->save()) {
                return Json::success('修改成功');
            }else{
                throw new Exception('修改失败');
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage(),$e->getCode());
        }
    }

    /**
     * 删除附件
     *
     * @return void
     */
    public function del()
    {
        try {
            $ids = request()->get('ids');
            if (!$ids) {
                throw new Exception("请选择需要删除的附件");
            }
            $data = explode(',',$ids);
            if (count($data) <= 0) {
                throw new Exception("选择附件失败");
            }
            $uploadMgr = new UploadsManager;
            foreach ($data as $id) {
                $model = ModelUploadify::where(['id'=> $id])->find();
                if ($model) {
                    // 删除云端附件
                    $uploadMgr->delete($model->path);
                    // 删除数据附件
                    $model->delete();
                }
            }
            return Json::success('附件删除成功');
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 移动附件
     *
     * @return void
     */
    public function move()
    {
        try {
            if (request()->method() !== 'PUT') {
                throw new Exception('请求类型错误');
            }
            $cate_id = request()->post('cate_id');
            $data = request()->post('ids');
            foreach ($data as $id)
            {
                $model = ModelUploadify::where(['id'=> $id])->find();
                $model->cid = $cate_id;
                $model->save();
            }
            return Json::success('移动至该分类完成');
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }
}